import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:p_location/common/constant/color_list.dart';
import 'package:p_location/common/constant/sp_key.dart';
import 'package:p_location/common/res/common_res.dart';
import 'package:p_location/common/widget/colorful_button.dart';
import 'package:p_location/net/dio_http_client.dart';
import 'package:p_location/net/net_listener_impl.dart';
import 'package:p_location/user/constants/user_http_url.dart';
import 'package:p_location/utils/shared_preferences_util.dart';
import 'package:p_location/utils/string_util.dart';
import 'package:p_location/utils/toast_util.dart';

class PageIpConfig extends StatefulWidget {
  @override
  _PageIpConfigState createState() => _PageIpConfigState();
}

class _PageIpConfigState extends State<PageIpConfig> {
  final TextEditingController _accountController = new TextEditingController();
  var dropdownValue = "http://";

  @override
  void initState() {
    super.initState();
    _readCachedAddress();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          elevation: 0,
          brightness: Brightness.dark,
          //设置为白色字体
          leading: IconButton(
              tooltip: '返回',
              icon: Icon(Icons.arrow_back_ios, color: Colors.white),
              onPressed: () {
                Navigator.of(context).pop();
              }),
          centerTitle: true,
          title: Text("本地端用户配置"),
        ),
        body: Column(
          children: [
            Container(
              margin: EdgeInsets.fromLTRB(15, 45, 15, 5),
              padding: EdgeInsets.all(5),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(3)),
                color: Color.fromARGB(10, 0, 0, 0),
              ),
              child: Container(
                height: 35,
                padding: EdgeInsets.all(5),
                child: Row(
                  children: [
                    Container(
                        width: 80.0,
//                        color:Colors.blue,
                        child: DropdownButton<String>(
                          value: dropdownValue,
                          icon: Icon(Icons.arrow_drop_down),
                          iconSize: 24,
                          iconEnabledColor: Colors.black,
                          dropdownColor: Colors.white,
                          underline: SizedBox(),
                          onChanged: (String newValue) async {
                            setState(() {
                              dropdownValue = newValue;
                            });
                          },
                          items: <String>['http://', 'https://']
                              .map<DropdownMenuItem<String>>((String value) {
                            return DropdownMenuItem<String>(
                              value: value,
                              child: Text(value,
                                  style: TextStyle(color: Colors.grey)),
                            );
                          }).toList(),
                        )),
//                    Icon(Icons.all_out),
                    Expanded(
                        flex: 1,
                        child: Container(
//                          color: Colors.red,
                          child: TextField(
                            controller: _accountController,
                            autofocus: true,
                            decoration: InputDecoration(
                                contentPadding:EdgeInsets.symmetric(vertical:9),
                                hintStyle: TextStyle(color: Colors.grey,fontSize: 15),
                                hintText: "请输入企业域名/ip端口地址",
//                                prefixIcon: Icon(Icons.account_circle),
//                                labelText: '请输入账号',
                                border: InputBorder.none
                                 /*OutlineInputBorder(borderRadius: BorderRadius.all(Radius.circular(30)),)*/ ),
                            style: TextStyle(
                                textBaseline: TextBaseline.alphabetic,
                                fontSize: 16),
//                            inputFormatters: [
//                              FilteringTextInputFormatter.allow(RegExp("[a-zA-Z]")),//只允许输入字母
//                            ],
                            onChanged: _inputChange,
                          ),
                        )),
                  ],
                ),
              ),
            ),
            Container(
              margin: EdgeInsets.fromLTRB(15, 5, 15, 5),
              child: Text(
                "说明：域名格式类似于www.baidu.com;ip端口格式类似于192.156.0.156:8888",
                style: TextStyle(color: ColorList.BLACK_45),
              ),
            ),
            ColorfulButton("确认", () {
              if (StringUtil.isEmpty(_accountController.text)) {
                ToastUtil.showToast("请填写ip地址");
                return;
              }
              print(dropdownValue);
              print(_accountController.text);
              _accountController.text = _accountController.text.replaceAll(new RegExp(r"\s+\b|\b\s"),"");
              String fullUrl = '$dropdownValue${_accountController.text}';
              if (!StringUtil.isValidIp(fullUrl)) {
                ToastUtil.showToast("请填写格式正确的ip地址或域名");
                return;
              }
              if (!fullUrl.endsWith("/")) {
                fullUrl = '$fullUrl/';
              }
              testConnection(fullUrl);
            })
          ],
        ));
  }

  _inputChange(String str) {
    setState(() {});
  }

  _saveAddress(String protocol, String address) {
    Map<String, String> buildInfo = {};
    buildInfo[SPKey.KEY_IP_PROTOCOL] = protocol;
    buildInfo[SPKey.KEY_IP_ADDRESS] = address;
    SharedPreferenceHelp.save(buildInfo);
  }

  _readCachedAddress() async {
    String protocol = await SharedPreferenceHelp.read(SPKey.KEY_IP_PROTOCOL);
    String address = await SharedPreferenceHelp.read(SPKey.KEY_IP_ADDRESS);
    if (StringUtil.isNotEmpty(protocol) && StringUtil.isNotEmpty(address)) {
      setState(() {
        dropdownValue = protocol;
        _accountController.text = address;
      });
    }
  }

  testConnection(String fullUrl) async {
    String last = '${DioHttpClient.baseUrl}';
    DioHttpClient.baseUrl = fullUrl;
    await DioHttpClient.requestPost(
        context,
        UserHttpUrl.GET_TEST_CONNECTION_URL,
        {},
        NetListenerImpl((response) {
          if (response != null && response.data != null) {
            DioHttpClient.baseUrl = fullUrl;
            if (!_accountController.text.endsWith("/")) {
              _accountController.text = '${_accountController.text}/';
            }
            _saveAddress(dropdownValue, _accountController.text);
            Navigator.of(context).pop();
          }
        }, (CommonRes errorRes) {
          DioHttpClient.baseUrl = last;
          ToastUtil.showToast("验证失败,请填写正确的ip地址或域名");
        }),loadingTip: "地址校验中,请稍候...");
  }
}
